<template>
  <div class="search-page">
    <div class="search-header">
      <div class="search-bar">
        <input 
          v-model="query" 
          @keyup.enter="onSearch" 
          placeholder="搜索商品、课程、教练..." 
          class="search-input"
        />
        <button @click="onSearch" class="search-btn">搜索</button>
        <button @click="startVoiceInput" class="voice-btn">🎤</button>
      </div>
      
      <!-- 搜索分类 -->
      <div class="search-categories">
        <button 
          v-for="category in categories" 
          :key="category.value"
          :class="['category-btn', { active: selectedCategory === category.value }]"
          @click="selectedCategory = category.value"
        >
          {{ category.label }}
        </button>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results">
      <div v-if="searching" class="loading">
        <div class="loading-spinner"></div>
        <p>搜索中...</p>
      </div>
      
      <!-- 推荐内容优先渲染，只在推荐和全部分类下显示 -->
      <div v-if="(selectedCategory === 'recommend' || selectedCategory === 'all') && recommendResults.length">
        <h3>推荐内容</h3>
        <div class="recommend-list">
          <RecommendCard
            v-for="item in recommendResults"
            :key="item.id + '-recommend'"
            :coverUrl="item.cover || item.cover_url"
            :title="item.title"
            :authorName="item.author"
            :videoUrl="item.video_url_web || item.video_url || ''"
            tag="推荐"
          />
        </div>
      </div>
      <!-- 商品分组，只在全部或商品分类下显示 -->
      <div v-if="(selectedCategory === 'all' || selectedCategory === 'products') && productResults.length">
        <h3>商品信息</h3>
        <div v-for="item in productResults" :key="item.id + '-product'" class="result-section">
          <div class="product-card">
            <span class="card-tag">商品</span>
            <img :src="item.cover || item.cover_image || '/default-avatar.png'" :alt="item.name" />
            <div class="product-info">
              <h5 v-html="highlightKeyword(item.name, query)" />
              <p class="price">￥{{ item.price }}</p>
            </div>
          </div>
        </div>
      </div>
      <!-- 课程分组，只在全部或课程分类下显示 -->
      <div v-if="(selectedCategory === 'all' || selectedCategory === 'courses') && courseResults.length">
        <h3>课程信息</h3>
        <div v-for="item in courseResults" :key="item.id + '-course'" class="result-section">
          <div class="course-card">
            <span class="card-tag">课程</span>
            <div class="course-info">
              <h5 v-html="highlightKeyword(item.title || item.name, query)" />
              <p v-html="highlightKeyword(item.description, query)" />
            </div>
          </div>
        </div>
      </div>
      <!-- 教练分组，只在全部或教练分类下显示 -->
      <div v-if="(selectedCategory === 'all' || selectedCategory === 'coaches') && coachResults.length">
        <h3>教练信息</h3>
        <div v-for="item in coachResults" :key="item.id + '-coach'" class="result-section">
          <div class="coach-card">
            <span class="card-tag">教练</span>
            <img :src="item.avatar || '/default-avatar.png'" :alt="item.author" />
            <div class="coach-info">
              <h5 v-html="highlightKeyword(item.author, query)" />
              <p v-html="highlightKeyword(item.specialty, query)" />
            </div>
          </div>
        </div>
      </div>
      <!-- 动态分组，只在全部或动态分类下显示 -->
      <div v-if="(selectedCategory === 'all' || selectedCategory === 'posts') && postResults.length">
        <h3>动态信息</h3>
        <div v-for="item in postResults" :key="item.id + '-post'" class="result-section">
          <div class="post-card">
            <span class="card-tag">动态</span>
            <div class="post-title" v-html="highlightKeyword(item.title, query)" />
            <div class="post-content" v-html="highlightKeyword(item.content, query)" />
            <div class="post-meta">作者：<span v-html="highlightKeyword(item.author, query)" /></div>
          </div>
        </div>
      </div>
      
      <div v-else-if="hasSearched" class="no-results">
        <p>没有找到相关结果</p>
        <p>试试其他关键词或分类</p>
      </div>
      
      <div v-else class="search-tips">
        <h3>搜索提示</h3>
        <ul>
          <li>可以搜索商品名称、课程类型、教练姓名</li>
          <li>支持语音输入，点击🎤按钮开始语音搜索</li>
          <li>使用分类筛选可以更精确地找到需要的内容</li>
          <li><strong>商品搜索</strong>：瑜伽垫、哑铃、跑步机、运动服、蛋白粉等</li>
          <li><strong>课程搜索</strong>：瑜伽、普拉提、力量训练、有氧运动、舞蹈、拳击等</li>
          <li><strong>教练搜索</strong>：张教练、李教练、王教练、刘教练、陈教练、赵教练等</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import request from '@/utils/request'
import RecommendCard from '../components/RecommendCard.vue'

const router = useRouter()
const route = useRoute()
const query = ref((route && route.query && route.query.q) || '')
const results = ref([])
const searching = ref(false)
const hasSearched = ref(false)
const selectedCategory = ref('all')

// 搜索分类
const categories = [
  { label: '全部', value: 'all' },
  { label: '商品', value: 'products' },
  { label: '课程', value: 'courses' },
  { label: '教练', value: 'coaches' },
  { label: '动态', value: 'posts' },
  { label: '推荐', value: 'recommend' }
]

// 首页 mock 数据（商品、课程、教练、动态）
const homeMockData = [
  // 商品
  { id: 1, type: 'product', name: '瑜伽垫', price: 99.99, cover: '/default-avatar.png' },
  { id: 2, type: 'product', name: '哑铃套装', price: 299.99, cover: '/default-avatar.png' },
  // 课程
  { id: 11, type: 'course', title: '瑜伽入门教程', description: '适合初学者的瑜伽课程' },
  { id: 12, type: 'course', title: '普拉提基础', description: '核心力量训练' },
  // 教练
  { id: 21, type: 'coach', author: '张教练', specialty: '瑜伽导师', avatar: '/default-avatar.png' },
  { id: 22, type: 'coach', author: '李教练', specialty: '力量训练', avatar: '/default-avatar.png' },
  // 动态
  { id: 31, type: 'post', title: '瑜伽练习分享', content: '今天练习了瑜伽，感觉身体很放松。', author: 'tieba' },
  { id: 32, type: 'post', title: '呼啦圈运动记录', content: '10.08呼啦圈40min（顺时针、逆时针各20min）踩车20min', author: 'tieba' }
]

// 计算属性：按分类筛选结果
const productResults = computed(() => results.value.filter(item => item.type === 'product'))
const courseResults = computed(() => results.value.filter(item => item.type === 'course'))
const coachResults = computed(() => results.value.filter(item => item.type === 'coach'))
const postResults = computed(() => results.value.filter(item => item.type === 'post' || item.type === 'dynamic'))
const recommendResults = computed(() => {
  // 先筛选出所有推荐内容
  const all = results.value.filter(item =>
    (item.cover || item.cover_url) &&
    item.title &&
    item.author
  )
  if (!query.value) return all
  // 有视频链接的排前面
  const videoList = all.filter(item => item.video_url_web || item.video_url)
  // 仅名称相关的排后面
  const nameList = all.filter(item =>
    !(item.video_url_web || item.video_url) &&
    (
      (item.title && item.title.includes(query.value)) ||
      (item.content && item.content.includes(query.value)) ||
      (item.name && item.name.includes(query.value)) ||
      (item.author && item.author.includes(query.value))
    )
  )
  // 其他无关内容不显示
  return [...videoList, ...nameList]
})

// 统计当前分类的结果数量
const currentResultsCount = computed(() => {
  if (selectedCategory.value === 'all') {
    // 包含所有类型，包括推荐内容
    return productResults.value.length + courseResults.value.length + coachResults.value.length + postResults.value.length + recommendResults.value.length
  } else if (selectedCategory.value === 'products') {
    return productResults.value.length
  } else if (selectedCategory.value === 'courses') {
    return courseResults.value.length
  } else if (selectedCategory.value === 'coaches') {
    return coachResults.value.length
  } else if (selectedCategory.value === 'posts') {
    return postResults.value.length
  } else if (selectedCategory.value === 'recommend') {
    return recommendResults.value.length
  }
  return 0
})

// 搜索函数
async function onSearch() {
  if (!query.value.trim()) {
    alert('请输入搜索内容')
    searching.value = false
    return
  }
  searching.value = true
  hasSearched.value = true
  try {
    const res = await request.get('/api/search/', { params: { q: query.value } })
    console.log('raw res:', res)
    console.log('raw res.data:', res.data)
    console.log('raw res.data.results:', res.data && res.data.results)
    let data = []
    if (Array.isArray(res)) {
      data = res
    } else if (Array.isArray(res.data)) {
      data = res.data
    } else if (Array.isArray(res.data?.results)) {
      data = res.data.results
    } else if (res.data && typeof res.data === 'object') {
      data = [res.data]
    }
    data = data.map(item => ({
      ...item,
      type: item.type || 'post'
    }))
    results.value = data
    console.log('search results:', results.value)
  } catch (e) {
    results.value = []
  }
  searching.value = false
}

// 语音输入
function startVoiceInput() {
  if (!('webkitSpeechRecognition' in window)) {
    alert('当前浏览器不支持语音识别')
    return
  }
  
  const recognition = new window.webkitSpeechRecognition()
  recognition.lang = 'zh-CN'
  recognition.continuous = false
  recognition.interimResults = false
  
  recognition.onresult = function(event) {
    if (event.results.length > 0) {
      let transcript = event.results[0][0].transcript
      // 去除末尾的句号、问号、感叹号等标点符号
      transcript = transcript.replace(/[。？！，、；：""''（）【】《》…—~`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+$/g, '')
      query.value = transcript
      onSearch()
    }
  }
  
  recognition.onerror = function(event) {
    console.error('语音识别错误:', event.error)
    if (event.error === 'no-speech') {
      alert('没有检测到语音，请重试')
    } else {
      alert('语音识别出错，请重试')
    }
  }
  
  recognition.onend = function() {
    console.log('语音识别结束')
  }
  
  recognition.start()
  console.log('开始语音识别...')
}

// 获取商品图片
function getProductImage(imagePath) {
  if (!imagePath) return '/default-avatar.png'
  if (imagePath.startsWith('http')) return imagePath
  return `http://127.0.0.1:8000/${imagePath}`
}

// 跳转函数
function goToProduct(id) {
  router.push(`/shop/${id}`)
}

function goToCourse(type) {
  router.push(`/course?type=${type}`)
}

function goToCoach(id) {
  router.push(`/coach?id=${id}`)
}

function goToPost(id) {
  router.push(`/community?id=${id}`)
}

function highlightKeyword(text, keyword) {
  if (!text || !keyword) return text
  // 转义正则特殊字符
  const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const pattern = new RegExp(escaped, 'gi')
  return text.replace(pattern, '<span style="color:red">$&</span>')
}

function openVideo(url) {
  if (url) {
    window.open(url, '_blank')
  }
}

onMounted(() => {
  if (query.value) {
    onSearch()
  }
})

watch(() => (route && route.query ? route.query.q : undefined), (newQ) => {
  if (typeof newQ === 'string') {
    query.value = newQ
    onSearch()
  }
})

watch(query, (val, oldVal) => {
  if (val && val !== oldVal) {
    onSearch()
  }
})
</script>

<style scoped>
.search-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-header {
  margin-bottom: 30px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 12px 16px;
  font-size: 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: #409eff;
}

.search-btn {
  padding: 12px 24px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.search-btn:hover {
  background: #337ecc;
}

.voice-btn {
  padding: 12px 16px;
  background: #67c23a;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.voice-btn:hover {
  background: #529b2e;
}

.search-categories {
  display: flex;
  gap: 10px;
}

.category-btn {
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  background: white;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.category-btn.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.loading {
  text-align: center;
  padding: 40px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.results-container {
  margin-top: 20px;
}

.results-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.result-section {
  margin-bottom: 30px;
}

.result-section h4 {
  margin-bottom: 15px;
  color: #333;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.product-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
}

.product-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.product-card img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.product-info {
  padding: 12px;
}

.product-info h5 {
  margin: 0 0 8px 0;
  font-size: 14px;
}

.price {
  color: #e74c3c;
  font-weight: bold;
  font-size: 16px;
}

.course-list, .coach-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.course-card, .coach-card {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.3s;
}

.course-card:hover, .coach-card:hover {
  background: #f5f5f5;
}

.course-icon {
  font-size: 24px;
  margin-right: 15px;
}

.course-info h5, .coach-info h5 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.course-info p, .coach-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.coach-card img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.no-results {
  text-align: center;
  padding: 40px;
  color: #666;
}

.search-tips {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
}

.search-tips h3 {
  margin-top: 0;
  color: #333;
}

.search-tips ul {
  margin: 10px 0;
  padding-left: 20px;
}

.search-tips li {
  margin-bottom: 5px;
  color: #666;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.post-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 18px 22px;
  cursor: pointer;
  transition: background 0.2s;
}

.post-card:hover {
  background: #f5f7fa;
}

.post-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 8px;
  color: #222;
}

.post-content {
  font-size: 1rem;
  color: #444;
  margin-bottom: 6px;
}

.post-meta {
  font-size: 0.95rem;
  color: #888;
}
/* 新增/修改样式：推荐、商品、课程、教练网格布局 */
.recommend-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 24px;
  width: 100%;
}
.recommend-list .recommend-card, .recommend-list > * {
  min-width: 0;
  width: 100%;
  box-sizing: border-box;
}
/* 推荐内容卡片样式自适应grid布局，减少空白 */
.recommend-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 16px;
  width: 100%;
  box-sizing: border-box;
  padding: 0;
}
.recommend-list .recommend-card, .recommend-list > * {
  width: 100%;
  min-width: 0;
  max-width: 100%;
  height: 320px;
  box-sizing: border-box;
}
/* 卡片分组标签样式 */
.card-tag {
  display: inline-block;
  background: #409eff;
  color: #fff;
  font-size: 12px;
  border-radius: 8px;
  padding: 2px 10px;
  margin-bottom: 6px;
  margin-right: 8px;
}
.search-results {
  min-height: 700px;
}
</style> 